<template>
  <div>
    <div class="min-h-screen flex flex-col">
      <!-- 顶部导航栏 -->
      <nav class="bg-emerald-600 text-white shadow-md">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
          <div class="flex items-center space-x-2">
            <i class="fas fa-leaf text-2xl"></i>
            <span class="text-xl font-bold">营养师后台管理系统</span>
          </div>
          <div class="flex items-center space-x-4">
            <a href="#" class="hover:text-emerald-200">
              <i class="fas fa-bell"></i>
              <span class="bg-red-500 text-white rounded-full w-5 h-5 text-xs flex items-center justify-center absolute -mt-8 ml-3">3</span>
            </a>
            <div class="relative group">
              <div class="flex items-center space-x-2 cursor-pointer">
                <img src="https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=150&h=150&q=80" 
                  class="w-8 h-8 rounded-full object-cover" 
                  crossorigin="anonymous"
                  alt="用户头像">
                <span>管理员</span>
                <i class="fas fa-chevron-down text-xs"></i>
              </div>
              <div class="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-50 hidden group-hover:block">
                <a href="#" class="block px-4 py-2 text-gray-800 hover:bg-emerald-100">
                  <i class="fas fa-user mr-2"></i>个人信息
                </a>
                <a href="#" class="block px-4 py-2 text-gray-800 hover:bg-emerald-100">
                  <i class="fas fa-cog mr-2"></i>系统设置
                </a>
                <div class="border-t border-gray-200 my-1"></div>
                <a href="#" class="block px-4 py-2 text-gray-800 hover:bg-emerald-100">
                  <i class="fas fa-sign-out-alt mr-2"></i>退出登录
                </a>
              </div>
            </div>
          </div>
        </div>
      </nav>

      <!-- 主要内容区 -->
      <div class="flex flex-1">
        <!-- 侧边导航 -->
        <SideNav />

        <!-- 主内容 -->
        <main class="flex-1 p-6">
          <div class="flex justify-between items-center mb-6">
            <h3 class="text-lg font-medium text-gray-900">用户列表</h3>
            <div class="flex gap-4">
              <!-- 添加用户按钮已移除 -->
              <div class="relative" ref="devToolsRef">
                <button type="button" @click="toggleDevTools" class="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500">
                  <i class="fas fa-tools mr-2"></i> 开发工具
                </button>
                
                <!-- 开发工具面板 -->
                <div v-if="showDevTools" class="absolute right-0 mt-2 w-64 bg-white shadow-lg rounded-md z-10 overflow-hidden">
                  <div class="px-4 py-3 bg-gray-50 text-sm font-medium text-gray-700 border-b">API 测试工具</div>
                  <div class="p-3 space-y-2">
                    <button @click="checkApiStatusHandler" class="w-full text-left px-3 py-2 text-sm rounded-md hover:bg-gray-100">
                      <i class="fas fa-check-circle mr-2 text-blue-500"></i> 检查 API 状态
                    </button>
                    <!-- 添加测试用户按钮已移除 -->
                    <div class="border-t pt-2 mt-2">
                      <button @click="refreshUserList" class="w-full text-left px-3 py-2 text-sm rounded-md hover:bg-gray-100">
                        <i class="fas fa-sync-alt mr-2 text-gray-500"></i> 刷新用户列表
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 数据卡片 -->
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
            <div class="bg-white rounded-lg shadow-md p-6">
              <div class="flex items-center justify-between">
                <div>
                  <p class="text-gray-500">总用户数</p>
                  <h3 class="text-3xl font-bold text-gray-800">{{ stats.totalUsers.current }}</h3>
                </div>
                <div class="bg-emerald-100 rounded-full w-12 h-12 flex items-center justify-center">
                  <i class="fas fa-users text-emerald-600 text-xl"></i>
                </div>
              </div>
              <p class="mt-4 text-sm" :class="stats.totalUsers.changeDirection === 'up' ? 'text-green-600' : 'text-red-600'">
                <i :class="['fas', stats.totalUsers.changeDirection === 'up' ? 'fa-arrow-up' : 'fa-arrow-down', 'mr-1']"></i> 
                {{ stats.totalUsers.changePercentage }}% 
                <span class="text-gray-500">对比上周期</span>
              </p>
            </div>
            
            <div class="bg-white rounded-lg shadow-md p-6">
              <div class="flex items-center justify-between">
                <div>
                  <p class="text-gray-500">活跃用户</p>
                  <h3 class="text-3xl font-bold text-gray-800">{{ stats.activeUsers.current }}</h3>
                </div>
                <div class="bg-blue-100 rounded-full w-12 h-12 flex items-center justify-center">
                  <i class="fas fa-user-check text-blue-600 text-xl"></i>
                </div>
              </div>
              <p class="mt-4 text-sm" :class="stats.activeUsers.changeDirection === 'up' ? 'text-green-600' : 'text-red-600'">
                <i :class="['fas', stats.activeUsers.changeDirection === 'up' ? 'fa-arrow-up' : 'fa-arrow-down', 'mr-1']"></i> 
                {{ stats.activeUsers.changePercentage }}% 
                <span class="text-gray-500">{{ stats.activeUsers.period === 'monthly' ? '上月' : '上周期' }}</span>
              </p>
            </div>
            
            <div class="bg-white rounded-lg shadow-md p-6">
              <div class="flex items-center justify-between">
                <div>
                  <p class="text-gray-500">新增用户</p>
                  <h3 class="text-3xl font-bold text-gray-800">{{ stats.newUsers.current }}</h3>
                </div>
                <div class="bg-purple-100 rounded-full w-12 h-12 flex items-center justify-center">
                  <i class="fas fa-user-plus text-purple-600 text-xl"></i>
                </div>
              </div>
              <p class="mt-4 text-sm" :class="stats.newUsers.changeDirection === 'up' ? 'text-green-600' : 'text-red-600'">
                <i :class="['fas', stats.newUsers.changeDirection === 'up' ? 'fa-arrow-up' : 'fa-arrow-down', 'mr-1']"></i> 
                {{ stats.newUsers.changePercentage }}% 
                <span class="text-gray-500">{{ stats.newUsers.period === 'monthly' ? '上月' : '上周期' }}</span>
              </p>
            </div>
            
            <div class="bg-white rounded-lg shadow-md p-6">
              <div class="flex items-center justify-between">
                <div>
                  <p class="text-gray-500">增长率</p>
                  <h3 class="text-3xl font-bold text-gray-800">{{ stats.growthRate.currentPercentage }}%</h3>
                </div>
                <div class="bg-amber-100 rounded-full w-12 h-12 flex items-center justify-center">
                  <i class="fas fa-chart-line text-amber-600 text-xl"></i>
                </div>
              </div>
              <p class="mt-4 text-sm" :class="stats.growthRate.changeDirection === 'up' ? 'text-green-600' : 'text-red-600'">
                <i :class="['fas', stats.growthRate.changeDirection === 'up' ? 'fa-arrow-up' : 'fa-arrow-down', 'mr-1']"></i> 
                {{ stats.growthRate.changePercentagePoint }}个百分点 
                <span class="text-gray-500">{{ stats.growthRate.period === 'monthly' ? '上月' : '上周期' }}</span>
              </p>
            </div>
          </div>

          <!-- 筛选和搜索 -->
          <div class="bg-white rounded-lg shadow-md p-4 mb-6">
            <div class="flex flex-wrap gap-4">
              <div class="relative flex-grow md:max-w-xs" ref="searchInputRef">
                <span class="absolute inset-y-0 left-0 flex items-center pl-3">
                  <i class="fas fa-search text-gray-400"></i>
                </span>
                <input type="text" v-model="searchQuery" 
                  @keyup.enter="applyFilters" 
                  @focus="showSearchHistory = searchHistory.length > 0" 
                  class="pl-10 pr-10 py-2 w-full rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" 
                  placeholder="搜索用户名、邮箱...">
                <button @click="applyFilters" class="absolute inset-y-0 right-0 px-3 flex items-center text-gray-500 hover:text-emerald-600">
                  <i class="fas fa-search"></i>
                </button>
                
                <!-- 搜索历史下拉框 -->
                <div v-if="showSearchHistory" class="absolute mt-1 w-full bg-white border border-gray-200 rounded-md shadow-lg py-1 z-10">
                  <div class="px-3 py-2 text-xs text-gray-500 border-b">搜索历史</div>
                  <div v-for="(item, index) in searchHistory" :key="index" 
                       @click="selectFromHistory(item)"
                       class="px-3 py-2 hover:bg-gray-100 cursor-pointer flex items-center">
                    <i class="fas fa-history text-gray-400 mr-2"></i>
                    <span>{{ item }}</span>
                  </div>
                  <div v-if="searchHistory.length > 0" class="px-3 py-2 text-xs text-right border-t">
                    <button @click="searchHistory = []; localStorage.removeItem('user_search_history'); showSearchHistory = false" 
                            class="text-gray-500 hover:text-gray-700">
                      清除历史
                    </button>
                  </div>
                </div>
              </div>
              
              <div class="flex flex-wrap items-center gap-3">
                <div class="relative">
                  <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                    <i class="fas fa-user-check text-gray-400"></i>
                  </div>
                  <select v-model="filters.isActive" @change="applyFilters" class="pl-9 pr-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500">
                    <option value="">所有活动状态</option>
                    <option value="true">活跃用户</option>
                    <option value="false">非活跃用户</option>
                  </select>
                </div>
                
                <div class="relative">
                  <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                    <i class="fas fa-user-tag text-gray-400"></i>
                  </div>
                  <select v-model="filters.role" @change="applyFilters" class="pl-9 pr-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500">
                    <option value="">所有用户角色</option>
                    <option value="user">普通用户</option>
                    <option value="admin">管理员</option>
                  </select>
                </div>
                
                <div class="relative">
                  <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                    <i class="fas fa-bullseye text-gray-400"></i>
                  </div>
                  <select v-model="filters.goal" @change="applyFilters" class="pl-9 pr-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500">
                    <option value="">所有目标</option>
                    <option value="weight_loss">减脂</option>
                    <option value="muscle_gain">增肌</option>
                    <option value="health">健康饮食</option>
                  </select>
                </div>
              </div>
              
              <div class="flex gap-2 ml-auto">
                <button v-if="hasActiveFilters" @click="resetFilters" class="border border-gray-300 hover:bg-gray-100 text-gray-700 px-4 py-2 rounded-md flex items-center">
                  <i class="fas fa-times mr-2"></i>清除筛选
                </button>
                <button @click="applyFilters" class="bg-emerald-600 hover:bg-emerald-700 text-white px-4 py-2 rounded-md flex items-center">
                  <i class="fas fa-filter mr-2"></i>筛选
                </button>
              </div>
            </div>

            <!-- 当前活跃筛选条件 -->
            <div v-if="hasActiveFilters" class="flex flex-wrap gap-2 mt-3">
              <span class="text-sm text-gray-600 mr-2">当前筛选:</span>
              <span v-if="filters.isActive" class="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full flex items-center">
                {{ filters.isActive === 'true' ? '活跃用户' : '非活跃用户' }}
                <button @click="clearFilter('isActive')" class="ml-1 text-blue-500 hover:text-blue-700">
                  <i class="fas fa-times-circle"></i>
                </button>
              </span>
              <span v-if="filters.role" class="px-2 py-1 bg-purple-100 text-purple-800 text-xs rounded-full flex items-center">
                {{ formatRole(filters.role) }}
                <button @click="clearFilter('role')" class="ml-1 text-purple-500 hover:text-purple-700">
                  <i class="fas fa-times-circle"></i>
                </button>
              </span>
              <span v-if="filters.goal" class="px-2 py-1 bg-green-100 text-green-800 text-xs rounded-full flex items-center">
                {{ formatGoal(filters.goal) }}
                <button @click="clearFilter('goal')" class="ml-1 text-green-500 hover:text-green-700">
                  <i class="fas fa-times-circle"></i>
                </button>
              </span>
              <span v-if="searchQuery" class="px-2 py-1 bg-amber-100 text-amber-800 text-xs rounded-full flex items-center">
                包含: "{{ searchQuery }}"
                <button @click="clearFilter('searchQuery')" class="ml-1 text-amber-500 hover:text-amber-700">
                  <i class="fas fa-times-circle"></i>
                </button>
              </span>
            </div>
          </div>

          <!-- 用户表格 -->
          <div class="bg-white rounded-lg shadow-md overflow-hidden">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50">
                <tr>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    <div class="flex items-center">
                      <input type="checkbox" v-model="selectAll" @change="toggleSelectAll" class="mr-2 rounded text-emerald-600 focus:ring-emerald-500">
                      用户信息
                    </div>
                  </th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    身体数据
                  </th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    目标
                  </th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    注册日期
                  </th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    状态
                  </th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    操作
                  </th>
                </tr>
              </thead>
              <tbody class="bg-white divide-y divide-gray-200">
                <tr v-if="loading" class="hover:bg-gray-50">
                  <td colspan="6" class="px-6 py-8 text-center text-gray-500">
                    <i class="fas fa-spinner fa-spin mr-2"></i> 正在加载用户数据...
                  </td>
                </tr>
                <tr v-else-if="userList.length === 0" class="hover:bg-gray-50">
                  <td colspan="6" class="px-6 py-8 text-center text-gray-500">
                    <div class="flex flex-col items-center justify-center">
                      <i class="fas fa-exclamation-circle text-2xl mb-2 text-gray-400"></i>
                      <p>暂无用户数据</p>
                      <p class="text-sm mt-1">可能原因：1. 数据库中没有用户数据 2. 当前筛选条件没有匹配结果 3. API连接问题</p>
                    </div>
                  </td>
                </tr>
                <tr v-for="user in userList" :key="user.id" class="hover:bg-gray-50">
                  <td class="px-6 py-4 whitespace-nowrap">
                    <div class="flex items-center">
                      <input type="checkbox" v-model="selectedUsers" :value="user.id" class="mr-2 rounded text-emerald-600 focus:ring-emerald-500">
                      <div class="flex-shrink-0 h-10 w-10">
                        <img class="h-10 w-10 rounded-full object-cover" 
                             :src="user.avatar" 
                             crossorigin="anonymous"
                             alt="用户头像">
                      </div>
                      <div class="ml-4">
                        <div class="text-sm font-medium text-gray-900">{{ user.name }}</div>
                        <div class="text-sm text-gray-500">{{ user.username }}</div>
                      </div>
                    </div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm text-gray-900">身高: {{ user.height }}cm</div>
                    <div class="text-sm text-gray-500">体重: {{ user.weight }}kg</div>
                    <div class="text-sm text-gray-500">年龄: {{ user.age }}</div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <span :class="goalClass(user.goal)">
                      {{ formatGoal(user.goal) }}
                    </span>
                    <div class="text-sm text-gray-500 mt-1">{{ user.dailyCalories }} kcal/日</div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {{ formatDate(user.registerDate) }}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <span :class="statusClass(user.status)">
                      {{ formatStatus(user.status) }}
                    </span>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div class="flex space-x-2">
                      <button @click="editUser(user)" class="text-emerald-600 hover:text-emerald-900">
                        <i class="fas fa-edit"></i>
                      </button>
                      <button @click="confirmDelete(user)" class="text-red-600 hover:text-red-900">
                        <i class="fas fa-trash-alt"></i>
                      </button>
                      <button @click="viewUserDetail(user)" class="text-blue-600 hover:text-blue-900">
                        <i class="fas fa-eye"></i>
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
            
            <!-- 分页 -->
            <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
              <div class="flex-1 flex justify-between sm:hidden">
                <button @click="prevPage" :disabled="currentPage === 1" class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50" :class="{ 'opacity-50 cursor-not-allowed': currentPage === 1 }">
                  上一页
                </button>
                <button @click="nextPage" :disabled="currentPage >= totalPages" class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50" :class="{ 'opacity-50 cursor-not-allowed': currentPage >= totalPages }">
                  下一页
                </button>
              </div>
              <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                <div>
                  <p class="text-sm text-gray-700">
                    显示 <span class="font-medium">{{ pagination.from }}</span> 到 <span class="font-medium">{{ pagination.to }}</span> 条，共 <span class="font-medium">{{ pagination.total }}</span> 条结果
                  </p>
                </div>
                <div>
                  <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                    <button @click="prevPage" :disabled="currentPage === 1" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50" :class="{ 'opacity-50 cursor-not-allowed': currentPage === 1 }">
                      <i class="fas fa-chevron-left"></i>
                    </button>
                    
                    <template v-for="(page, index) in displayedPages">
                      <span v-if="page === '...'" :key="'ellipsis-'+index" class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700">
                        ...
                      </span>
                      <button 
                        v-else
                        :key="'page-'+page"
                        @click="goToPage(page)"
                        class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium"
                        :class="page === currentPage ? 'bg-emerald-50 text-emerald-600 hover:bg-emerald-50' : 'bg-white text-gray-700 hover:bg-gray-50'"
                      >
                        {{ page }}
                      </button>
                    </template>
                    
                    <button @click="nextPage" :disabled="currentPage >= totalPages" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50" :class="{ 'opacity-50 cursor-not-allowed': currentPage >= totalPages }">
                      <i class="fas fa-chevron-right"></i>
                    </button>
                  </nav>
                </div>
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>

    <!-- 编辑用户模态框 (原添加/编辑模态框，现仅用于编辑) -->
    <div v-if="showEditUserModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-lg w-full max-w-3xl mx-4 overflow-hidden">
        <!-- 模态框标题 -->
        <div class="bg-emerald-600 text-white px-6 py-4 flex justify-between items-center">
          <h3 class="text-lg font-medium">编辑用户信息</h3>
          <button @click="closeEditUserModal" type="button" class="text-white hover:text-gray-200 focus:outline-none">
            <i class="fas fa-times"></i>
          </button>
        </div>

        <!-- 表单内容 (密码相关字段已移除) -->
        <div class="px-6 py-4 max-h-[80vh] overflow-y-auto">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- 基本信息 -->
            <div>
              <h4 class="text-md font-medium text-gray-700 mb-4">基本信息</h4>

              <!-- 用户名 -->
              <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1" for="username">
                  用户名 <span class="text-red-500">*</span>
                </label>
                <input type="text" id="username" v-model="userForm.username" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" placeholder="请输入用户名">
                <p v-if="formErrors.username" class="mt-1 text-sm text-red-600">{{ formErrors.username }}</p>
              </div>

              <!-- 昵称 -->
              <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1" for="nickname">
                  昵称 <span class="text-red-500">*</span>
                </label>
                <input type="text" id="nickname" v-model="userForm.nickname" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" placeholder="请输入昵称">
                <p v-if="formErrors.nickname" class="mt-1 text-sm text-red-600">{{ formErrors.nickname }}</p>
              </div>

              <!-- 电子邮箱 -->
              <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1" for="email">
                  电子邮箱
                </label>
                <input type="email" id="email" v-model="userForm.email" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" placeholder="请输入电子邮箱">
                <p v-if="formErrors.email" class="mt-1 text-sm text-red-600">{{ formErrors.email }}</p>
              </div>

              <!-- 头像选择 -->
              <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1">
                  选择头像
                </label>
                <div class="flex mt-2 items-center">
                  <div 
                    class="w-24 h-24 rounded-full cursor-pointer overflow-hidden border border-dashed border-gray-300 flex flex-col items-center justify-center text-gray-400 hover:text-gray-500 hover:border-emerald-500"
                    @click="triggerAvatarUpload"
                  >
                    <i class="fas fa-plus text-2xl mb-1"></i>
                    <span class="text-xs">上传头像</span>
                  </div>
                  <input type="file" ref="avatarInputRef" @change="handleAvatarFileChange" accept="image/jpeg,image/png,image/gif,image/webp" class="hidden">
                  <div v-if="userForm.avatar" class="ml-4">
                    <p class="text-xs text-gray-500 mb-1">当前头像:</p>
                    <img :src="getFullAvatarUrl(userForm.avatar)" class="w-24 h-24 rounded-full object-cover border" alt="当前用户头像">
                  </div>
                </div>
                 <p v-if="!userForm.avatar" class="mt-2 text-xs text-gray-500">请上传头像。支持 JPG, PNG, GIF, WEBP 格式，大小不超过 5MB。</p>
              </div>
            </div>

            <!-- 身体信息与目标 (与之前一致) -->
            <div>
              <h4 class="text-md font-medium text-gray-700 mb-4">身体数据与目标</h4>
              <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1">
                  性别
                </label>
                <div class="flex space-x-4">
                  <label class="inline-flex items-center">
                    <input type="radio" v-model="userForm.gender" value="男" class="form-radio text-emerald-600 focus:ring-emerald-500">
                    <span class="ml-2">男</span>
                  </label>
                  <label class="inline-flex items-center">
                    <input type="radio" v-model="userForm.gender" value="女" class="form-radio text-emerald-600 focus:ring-emerald-500">
                    <span class="ml-2">女</span>
                  </label>
                </div>
              </div>
              <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1" for="height">
                  身高 (cm) <span class="text-red-500">*</span>
                </label>
                <input type="number" id="height" v-model="userForm.height" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" placeholder="请输入身高">
                <p v-if="formErrors.height" class="mt-1 text-sm text-red-600">{{ formErrors.height }}</p>
              </div>
              <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1" for="weight">
                  体重 (kg) <span class="text-red-500">*</span>
                </label>
                <input type="number" id="weight" v-model="userForm.weight" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" placeholder="请输入体重">
                <p v-if="formErrors.weight" class="mt-1 text-sm text-red-600">{{ formErrors.weight }}</p>
              </div>
              <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1" for="age">
                  年龄 <span class="text-red-500">*</span>
                </label>
                <input type="number" id="age" v-model="userForm.age" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" placeholder="请输入年龄">
                <p v-if="formErrors.age" class="mt-1 text-sm text-red-600">{{ formErrors.age }}</p>
              </div>
              <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1" for="goal">
                  饮食目标
                </label>
                <select id="goal" v-model="userForm.goal" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500">
                  <option value="weight_loss">减脂</option>
                  <option value="muscle_gain">增肌</option>
                  <option value="health">健康饮食</option>
                </select>
              </div>
              <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1" for="activityLevel">
                  活动水平
                </label>
                <select id="activityLevel" v-model="userForm.activityLevel" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500">
                  <option value="1">久坐不动</option>
                  <option value="2">轻度活动</option>
                  <option value="3">中度活动</option>
                  <option value="4">高度活动</option>
                  <option value="5">极高活动量</option>
                </select>
                <p class="mt-1 text-xs text-gray-500">活动水平将影响每日卡路里推荐值</p>
              </div>
              <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1" for="role">
                  用户角色
                </label>
                <select id="role" v-model="userForm.role" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500">
                  <option value="user">普通用户</option>
                  <option value="admin">管理员</option>
                </select>
              </div>
              <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1" for="dailyCalories">
                  每日卡路里 (kcal) <span class="text-red-500">*</span>
                </label>
                <input type="number" id="dailyCalories" v-model="userForm.dailyCalories" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" placeholder="请输入每日卡路里目标">
                <p v-if="formErrors.dailyCalories" class="mt-1 text-sm text-red-600">{{ formErrors.dailyCalories }}</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 按钮区域 -->
        <div class="bg-gray-50 px-6 py-4 flex justify-end space-x-3">
          <button type="button" @click="closeEditUserModal" class="bg-white border border-gray-300 text-gray-700 px-4 py-2 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">
            取消
          </button>
          <button type="button" @click="saveUser" class="bg-emerald-600 text-white px-4 py-2 rounded-md hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2">
            保存修改
          </button>
        </div>
      </div>
    </div>

    <!-- 删除确认对话框 (保留) -->
    <div v-if="showDeleteConfirm" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-lg max-w-md mx-4 overflow-hidden">
        <div class="bg-red-600 text-white px-6 py-4">
          <h3 class="text-lg font-medium">确认删除</h3>
        </div>
        <div class="px-6 py-4">
          <p class="text-gray-700">您确定要删除用户 <span class="font-semibold">{{ userToDelete && userToDelete.name }}</span> 吗？此操作不可撤销。</p>
        </div>
        <div class="bg-gray-50 px-6 py-4 flex justify-end space-x-3">
          <button type="button" @click="showDeleteConfirm = false" class="bg-white border border-gray-300 text-gray-700 px-4 py-2 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">
            取消
          </button>
          <button type="button" @click="deleteUser" class="bg-red-600 text-white px-4 py-2 rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2">
            确认删除
          </button>
        </div>
      </div>
    </div>

    <!-- 信息模态框 -->
    <InfoModal 
      :visible="showInfoModal" 
      :title="infoModalTitle" 
      :message="infoModalMessage" 
      :success="infoModalSuccess"
      @close="showInfoModal = false"
    />

    <!-- 用户详情模态框 -->
    <UserDetailModal
      :user="selectedUserForDetail"
      :visible="showUserDetailModal"
      @close="showUserDetailModal = false; selectedUserForDetail = null;"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { 
  getUserList, 
  // getUserStats, // 旧的API调用，将被替换
  updateUser, 
  deleteUser as apiDeleteUser,
  uploadAvatar,
  getUserDetail,
  getUserDashboardSummaryStats // 导入新的API函数
} from '@/api/user'
import SideNav from '@/components/SideNav.vue'
import InfoModal from '@/components/InfoModal.vue'
import UserDetailModal from '@/components/UserDetailModal.vue'
import { checkApiStatus /*, addTestUser, addMultipleTestUsers*/ } from '@/utils/api-test' // 移除了测试用户添加工具

// 文件输入引用
const avatarInputRef = ref(null)

// 信息模态框状态
const showInfoModal = ref(false)
const infoModalTitle = ref('')
const infoModalMessage = ref('')
const infoModalSuccess = ref(true)

// 用户详情模态框状态
const showUserDetailModal = ref(false)
const selectedUserForDetail = ref(null)

// 编辑用户模态框状态 (原添加/编辑模态框，现仅用于编辑)
const showEditUserModal = ref(false) // 重命名 showAddUserModal
// const isEditing = ref(false) // 此状态不再需要，因为总是编辑模式
const userForm = reactive({
  id: null,
  username: '',
  nickname: '',
  // password: '', // 密码相关字段已移除
  // confirmPassword: '',
  gender: '男',
  height: '',
  weight: '',
  age: '',
  goal: 'weight_loss',
  role: 'user',
  dailyCalories: '',
  avatar: '',
  email: '',
  activityLevel: 2 
})
const formErrors = reactive({})

// ... (其他 ref 和 reactive 声明)
// 辅助函数：获取完整的头像URL
// ... (代码与之前一致)
const getFullAvatarUrl = (relativePath) => {
  console.log('[getFullAvatarUrl] Original relativePath:', relativePath);
  if (!relativePath || typeof relativePath !== 'string' || relativePath.startsWith('http')) {
    console.log('[getFullAvatarUrl] Returning as is (already full URL or invalid):', relativePath);
    return relativePath; 
  }
  const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api';
  console.log('[getFullAvatarUrl] VITE_API_BASE_URL or default:', apiBaseUrl);
  
  let serverRoot = apiBaseUrl;
  if (apiBaseUrl.endsWith('/api')) {
    serverRoot = apiBaseUrl.substring(0, apiBaseUrl.length - '/api'.length);
  }
  console.log('[getFullAvatarUrl] Deduced serverRoot:', serverRoot);

  const correctedRelativePath = relativePath.startsWith('/') ? relativePath : `/${relativePath}`;
  const fullUrl = `${serverRoot}${correctedRelativePath}`;
  console.log('[getFullAvatarUrl] Constructed fullUrl:', fullUrl);
  return fullUrl;
};

// 用户统计数据 - 更新结构以匹配新API
const stats = reactive({
  totalUsers: { current: 0, changePercentage: 0, changeDirection: 'up' },
  activeUsers: { current: 0, period: 'monthly', changePercentage: 0, changeDirection: 'up' },
  newUsers: { current: 0, period: 'monthly', changePercentage: 0, changeDirection: 'up' },
  growthRate: { currentPercentage: 0, period: 'monthly', changePercentagePoint: 0, changeDirection: 'up' }
})

// 用户列表数据
const userList = ref([])
const loading = ref(false)
const searchQuery = ref('')
const searchHistory = ref([])
const showSearchHistory = ref(false)
const filters = reactive({
  isActive: '',
  role: '',
  goal: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const pagination = reactive({
  total: 0,
  from: 0,
  to: 0,
  totalPages: 0
})

// 排序
const sortBy = ref('createdAt:desc')

// 计算总页数
const totalPages = computed(() => pagination.totalPages)

// 计算要显示的页码
const displayedPages = computed(() => {
  const pages = []
  const maxDisplayed = 5 
  
  if (totalPages.value <= maxDisplayed) {
    for (let i = 1; i <= totalPages.value; i++) {
      pages.push(i)
    }
  } else {
    pages.push(1) 
    
    if (currentPage.value <= 3) {
      for (let i = 2; i <= 4; i++) {
        if (i <= totalPages.value) pages.push(i)
      }
      pages.push('...')
    } else if (currentPage.value >= totalPages.value - 2) {
      pages.push('...')
      for (let i = totalPages.value - 3; i < totalPages.value; i++) {
        if (i > 1) pages.push(i)
      }
    } else {
      pages.push('...')
      for (let i = currentPage.value - 1; i <= currentPage.value + 1; i++) {
        if (i > 1 && i < totalPages.value) pages.push(i)
      }
      pages.push('...')
    }
    
    if (totalPages.value > 1) {
      pages.push(totalPages.value) 
    }
  }
  
  return pages
})

// 选择功能
const selectedUsers = ref([])
const selectAll = ref(false)

// 删除确认
const showDeleteConfirm = ref(false)
const userToDelete = ref(null)


// 开发工具相关
const showDevTools = ref(false);
const devToolsRef = ref(null);
const searchInputRef = ref(null);

function toggleDevTools() {
  showDevTools.value = !showDevTools.value;
}

function handleClickOutside(event) {
  if (devToolsRef.value && !devToolsRef.value.contains(event.target)) {
    showDevTools.value = false;
  }
  
  if (showSearchHistory.value && searchInputRef.value && !searchInputRef.value.contains(event.target)) {
    showSearchHistory.value = false;
  }
}

async function checkApiStatusHandler() {
  try {
    const result = await checkApiStatus();
    if (result.status === 'success') {
      infoModalTitle.value = 'API状态';
      infoModalMessage.value = 'API连接正常';
      infoModalSuccess.value = true;
    } else {
      infoModalTitle.value = 'API状态';
      infoModalMessage.value = `API连接失败: ${result.message}`;
      infoModalSuccess.value = false;
    }
    showInfoModal.value = true;
    showDevTools.value = false;
  } catch (error) {
    console.error('API状态检查失败', error);
    infoModalTitle.value = '操作失败';
    infoModalMessage.value = 'API状态检查失败';
    infoModalSuccess.value = false;
    showInfoModal.value = true;
  }
}

// addOneTestUser 和 addTestUsers 方法已移除

function refreshUserList() {
  fetchUserList();
  showDevTools.value = false;
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside);
});

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside);
});

onMounted(async () => {
  console.log('UsersView组件已挂载');
  initFiltersFromURL();
  loadSearchHistory();
  try {
    await fetchDashboardSummary(); // 调用更新后的函数
  } catch (error) {
    // fetchDashboardSummary 内部已经处理了错误并设置了默认值，这里可以只记录日志
    console.error('仪表盘统计数据获取失败（onMounted 调用处）:', error);
  }
  try {
    await fetchUserList();
  } catch (error) {
    console.error('用户列表获取失败，但允许页面继续显示:', error);
    userList.value = [];
  }
});

function initFiltersFromURL() {
  const urlParams = new URLSearchParams(window.location.search);
  const searchParam = urlParams.get('search');
  if (searchParam) {
    searchQuery.value = searchParam;
  }
  const isActiveParam = urlParams.get('isActive');
  if (isActiveParam) {
    filters.isActive = isActiveParam;
  }
  const roleParam = urlParams.get('role');
  if (roleParam) {
    filters.role = roleParam;
  }
  const goalParam = urlParams.get('goal');
  if (goalParam) {
    filters.goal = goalParam;
  }
}

// 获取用户仪表盘统计数据 (原 fetchUserStats)
async function fetchDashboardSummary() {
  try {
    const responseBody = await getUserDashboardSummaryStats() // 调用新的API函数
    if (responseBody && responseBody.error === 0 && responseBody.body) {
      const summaryData = responseBody.body;
      // 使用可选链和默认值确保健壮性
      stats.totalUsers = summaryData.totalUsers || { current: 0, changePercentage: 0, changeDirection: 'up' };
      stats.activeUsers = summaryData.activeUsers || { current: 0, period: 'monthly', changePercentage: 0, changeDirection: 'up' };
      stats.newUsers = summaryData.newUsers || { current: 0, period: 'monthly', changePercentage: 0, changeDirection: 'up' };
      stats.growthRate = summaryData.growthRate || { currentPercentage: 0, period: 'monthly', changePercentagePoint: 0, changeDirection: 'up' };
      console.log('仪表盘统计数据已更新:', stats);
    } else {
      console.warn('获取用户仪表盘统计摘要数据格式不符或有错误:', responseBody)
      // 出错或格式不符时，重置为默认结构以避免UI渲染错误
      Object.assign(stats, {
        totalUsers: { current: 0, changePercentage: 0, changeDirection: 'up' },
        activeUsers: { current: 0, period: 'monthly', changePercentage: 0, changeDirection: 'up' },
        newUsers: { current: 0, period: 'monthly', changePercentage: 0, changeDirection: 'up' },
        growthRate: { currentPercentage: 0, period: 'monthly', changePercentagePoint: 0, changeDirection: 'up' }
      });
    }
  } catch (error) {
    console.error('获取用户仪表盘统计摘要失败:', error)
    // 捕获到异常时也重置为默认结构
    Object.assign(stats, {
      totalUsers: { current: 0, changePercentage: 0, changeDirection: 'up' },
      activeUsers: { current: 0, period: 'monthly', changePercentage: 0, changeDirection: 'up' },
      newUsers: { current: 0, period: 'monthly', changePercentage: 0, changeDirection: 'up' },
      growthRate: { currentPercentage: 0, period: 'monthly', changePercentagePoint: 0, changeDirection: 'up' }
    });
  }
}

async function fetchUserList() {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value
    }
    if (searchQuery.value.trim()) {
      params.search = searchQuery.value.trim()
    }
    if (filters.isActive) {
      params.isActive = filters.isActive;
    }
    if (filters.role) {
      params.role = formatRoleForAPI(filters.role)
    }
    if (filters.goal) {
      params.goal = formatGoalForAPI(filters.goal)
    }
    if (sortBy.value) {
      params.sortBy = sortBy.value
    }
    console.log('应用筛选条件:', {
      关键词: searchQuery.value || '无',
      活跃状态: filters.isActive || '全部',
      用户角色: filters.role ? formatRoleForAPI(filters.role) : '全部',
      目标: filters.goal ? formatGoal(filters.goal) : '全部'
    });
    console.log('正在发送用户列表请求，参数:', params);
    const response = await getUserList(params);
    console.log('用户列表API响应:', response);
    
    if (response && response.data) {
      console.log('响应数据结构:', JSON.stringify(response.data, null, 2));
      const responseData = response.data;
      const results = responseData.body?.results || responseData.results || [];
      
      userList.value = Array.isArray(results) 
        ? results.map(user => ({
          id: user._id || user.id,
          name: user.name,
          username: user.nickname || user.name,
            avatar: getFullAvatarUrl(user.avatar) || '',
          height: user.height || 0,
          weight: user.weight || 0,
          age: user.age || 0,
          goal: formatGoalFromAPI(user.goal),
          role: formatRoleFromAPI(user.role || 'normal'),
          dailyCalories: user.dailyCalorieGoal || 0,
          registerDate: formatAPIDate(user.createdAt),
          status: user.isActive ? 'active' : 'inactive',
          gender: user.gender === 1 ? '男' : '女',
            email: user.email || '',
            activityLevel: user.activityLevel || 2
          }))
        : [];
      
        const totalResults = responseData.body?.totalResults || responseData.totalResults || 0;
      const totalPagesNum = responseData.body?.totalPages || responseData.totalPages || 1;
        
        pagination.total = totalResults;
      pagination.totalPages = totalPagesNum;
        pagination.from = totalResults > 0 ? (currentPage.value - 1) * pageSize.value + 1 : 0;
        pagination.to = Math.min(currentPage.value * pageSize.value, totalResults);
      
      if (results.length === 0) {
        console.log('API返回了空数据数组 - 这可能是正常的，没有匹配的结果');
      }
    } else {
      console.warn('API响应格式不符合预期:', response);
      userList.value = [];
      pagination.total = 0;
      pagination.totalPages = 0;
      pagination.from = 0;
      pagination.to = 0;
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    console.error('错误详情:', {
      message: error.message,
      response: error.response,
      stack: error.stack
    });
    userList.value = [];
    pagination.total = 0;
    pagination.totalPages = 0;
    pagination.from = 0;
    pagination.to = 0;
  } finally {
    loading.value = false;
  }
}

function formatGoalFromAPI(goal) {
  const goals = {
    '减脂': 'weight_loss',
    '增肌': 'muscle_gain',
    '健康饮食': 'health'
  }
  return goals[goal] || 'health'
}

function formatGoalForAPI(goal) {
  const goals = {
    'weight_loss': '减脂',
    'muscle_gain': '增肌',
    'health': '健康饮食'
  }
  return goals[goal] || '健康饮食'
}

function formatRoleForAPI(role) {
  return role;
}

function formatRoleFromAPI(role) {
  return role;
}

function formatAPIDate(dateString) {
  if (!dateString) return '未知'
  try {
    return new Date(dateString).toISOString().split('T')[0]
  } catch (e) {
    return '未知'
  }
}

function prevPage() {
  if (currentPage.value > 1) {
    currentPage.value--
    updateURLParams()
    fetchUserList()
  }
}

function nextPage() {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    updateURLParams()
    fetchUserList()
  }
}

function goToPage(page) {
  if (typeof page === 'number' && page !== currentPage.value) {
    currentPage.value = page
    updateURLParams()
    fetchUserList()
  }
}

function toggleSelectAll() {
  if (selectAll.value) {
    selectedUsers.value = userList.value.map(user => user.id)
  } else {
    selectedUsers.value = []
  }
}

const hasActiveFilters = computed(() => {
  return filters.isActive !== '' || filters.role !== '' || filters.goal !== '' || searchQuery.value !== '';
});

function applyFilters() {
  console.log('应用筛选条件:', {
    searchQuery: searchQuery.value,
    isActive: filters.isActive,
    role: filters.role,
    goal: filters.goal
  });
  if (searchQuery.value.trim()) {
    saveToSearchHistory(searchQuery.value);
  }
  currentPage.value = 1;
  updateURLParams();
  fetchUserList();
}

function resetFilters() {
  Object.keys(filters).forEach(key => {
    filters[key] = '';
  });
  searchQuery.value = '';
  currentPage.value = 1;
  updateURLParams();
  fetchUserList();
}

function clearFilter(filterName) {
  if (filterName === 'searchQuery') {
    searchQuery.value = '';
  } else {
    filters[filterName] = '';
  }
  currentPage.value = 1;
  updateURLParams();
  fetchUserList();
}

function updateURLParams() {
  const params = new URLSearchParams();
  if (searchQuery.value) {
    params.set('search', searchQuery.value);
  }
  if (filters.isActive) {
    params.set('isActive', filters.isActive);
  }
  if (filters.role) {
    params.set('role', filters.role);
  }
  if (filters.goal) {
    params.set('goal', filters.goal);
  }
  if (currentPage.value > 1) {
    params.set('page', currentPage.value.toString());
  }
  const newUrl = params.toString() 
    ? `${window.location.pathname}?${params.toString()}`
    : window.location.pathname;
  window.history.pushState({}, '', newUrl);
}

function formatDate(dateString) {
  return dateString || '未知'
}

function formatGoal(goal) {
  const goals = {
    'weight_loss': '减脂',
    'muscle_gain': '增肌',
    'health': '健康饮食'
  }
  return goals[goal] || goal
}

function formatRole(role) {
  const roles = {
    'user': '普通用户',
    'admin': '管理员'
  }
  return roles[role] || role
}

function formatStatus(status) {
  const statuses = {
    'active': '活跃',
    'inactive': '非活跃'
  }
  return statuses[status] || status
}

function goalClass(goal) {
  const classes = {
    'weight_loss': 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-purple-100 text-purple-800',
    'muscle_gain': 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800',
    'health': 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800'
  }
  return classes[goal] || 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800'
}

function statusClass(status) {
  return status === 'active' 
    ? 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800' 
    : 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800'
}

// 模态框相关方法
// openAddUserModal 和 isEditing 相关的逻辑已移除，因为现在模态框仅用于编辑

function closeEditUserModal() {
  showEditUserModal.value = false
  resetUserForm()
}

function resetUserForm() {
  Object.assign(userForm, {
    id: null,
    username: '',
    nickname: '',
    // password 和 confirmPassword 已移除
    gender: '男',
    height: '',
    weight: '',
    age: '',
    goal: 'weight_loss',
    role: 'user',
    dailyCalories: '',
    avatar: '', 
    email: '',
    activityLevel: 2
  })
  Object.keys(formErrors).forEach(key => formErrors[key] = '')
}


function editUser(user) {
  resetUserForm()
  Object.assign(userForm, {
    id: user.id,
    username: user.username,
    nickname: user.name,
    gender: user.gender || '男',
    height: user.height,
    weight: user.weight,
    age: user.age,
    goal: user.goal,
    role: user.role || 'user',
    dailyCalories: user.dailyCalories,
    avatar: user.avatar || '',
    email: user.email || '',
    activityLevel: user.activityLevel || 2
  })
  showEditUserModal.value = true // 直接显示编辑模态框
}

function confirmDelete(user) {
  userToDelete.value = user
  showDeleteConfirm.value = true
}

async function deleteUser() {
  if (!userToDelete.value) return
  try {
    await apiDeleteUser(userToDelete.value.id)
    await fetchUserList() 
    infoModalTitle.value = '操作成功';
    infoModalMessage.value = '用户删除成功！';
    infoModalSuccess.value = true;
    showInfoModal.value = true;
  } catch (error) {
    console.error('删除用户失败:', error)
    infoModalTitle.value = '操作失败';
    infoModalMessage.value = '删除用户失败: ' + (error.message || '未知错误');
    infoModalSuccess.value = false;
    showInfoModal.value = true;
  } finally {
    showDeleteConfirm.value = false
    userToDelete.value = null
  }
}

async function viewUserDetail(userInList) {
  if (!userInList || !userInList.id) {
    console.error('viewUserDetail: Invalid user object provided', userInList);
    infoModalTitle.value = '查看失败';
    infoModalMessage.value = '无法获取用户信息：用户ID无效。';
    infoModalSuccess.value = false;
    showInfoModal.value = true;
    return;
  }
  selectedUserForDetail.value = null; 
  showUserDetailModal.value = true;

  try {
    const response = await getUserDetail(userInList.id);
    if (response && response.data && response.data.error === 0 && response.data.body) {
      const detailedUser = response.data.body;
      selectedUserForDetail.value = {
        id: detailedUser._id || detailedUser.id,
        name: detailedUser.name,
        username: detailedUser.nickname || detailedUser.name,
        avatar: getFullAvatarUrl(detailedUser.avatar), 
        height: detailedUser.height || 0,
        weight: detailedUser.weight || 0,
        age: detailedUser.age || 0,
        goal: detailedUser.goal, 
        role: detailedUser.role || 'user',
        dailyCalories: detailedUser.dailyCalorieGoal || 0,
        registerDate: formatAPIDate(detailedUser.createdAt),
        status: detailedUser.isActive ? 'active' : 'inactive',
        gender: detailedUser.gender === 1 ? '男' : (detailedUser.gender === 2 ? '女' : '未知'),
        email: detailedUser.email || '',
        activityLevel: detailedUser.activityLevel || null, 
      };
    } else {
      throw new Error(response?.data?.message || '获取用户详细信息失败');
    }
  } catch (error) {
    console.error('查看用户详情失败:', error);
    showUserDetailModal.value = false;
    infoModalTitle.value = '操作失败';
    infoModalMessage.value = '查看用户详情失败: ' + (error.response?.data?.message || error.message || '未知错误');
    infoModalSuccess.value = false;
    showInfoModal.value = true;
  } finally {
  }
}

function validateForm() {
  let isValid = true
  Object.keys(formErrors).forEach(key => formErrors[key] = '')
  
  // 验证用户名
  if (!userForm.username || userForm.username.trim() === '') {
    formErrors.username = '请输入用户名'
    isValid = false
  }
  
  // 验证昵称
  if (!userForm.nickname || userForm.nickname.trim() === '') {
    formErrors.nickname = '请输入昵称'
    isValid = false
  }
  
  // 验证邮箱格式（如果提供了邮箱）
  if (userForm.email && typeof userForm.email === 'string' && userForm.email.trim()) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(userForm.email.trim())) {
      formErrors.email = '请输入有效的电子邮箱地址'
      isValid = false
    }
  } else if (userForm.email && typeof userForm.email === 'string' && userForm.email.trim() === '' && userForm.email !== '') {
    // This case handles if email was originally just whitespace but not an empty string. 
    // However, email is not mandatory, so this specific error might not be needed unless specified.
    // For now, just ensuring no trim on undefined. The above check handles format if non-empty.
  }
  
  // 密码验证已移除，因为不再通过此表单设置密码
  if (!userForm.height) {
    formErrors.height = '请输入身高'
    isValid = false
  } else if (isNaN(userForm.height) || Number(userForm.height) <= 0) {
    formErrors.height = '请输入有效的身高数值'
    isValid = false
  }
  if (!userForm.weight) {
    formErrors.weight = '请输入体重'
    isValid = false
  } else if (isNaN(userForm.weight) || Number(userForm.weight) <= 0) {
    formErrors.weight = '请输入有效的体重数值'
    isValid = false
  }
  if (!userForm.age) {
    formErrors.age = '请输入年龄'
    isValid = false
  } else if (isNaN(userForm.age) || Number(userForm.age) <= 0) {
    formErrors.age = '请输入有效的年龄数值'
    isValid = false
  }
  if (!userForm.dailyCalories) {
    formErrors.dailyCalories = '请输入每日卡路里'
    isValid = false
  } else if (isNaN(userForm.dailyCalories) || Number(userForm.dailyCalories) <= 0) {
    formErrors.dailyCalories = '请输入有效的卡路里数值'
    isValid = false
  }
  return isValid
}

async function saveUser() {
  if (!validateForm()) return
  
  try {
    // 仅处理编辑用户逻辑
      const userData = {
        name: userForm.nickname,
        nickname: userForm.username,
        gender: userForm.gender === '男' ? 1 : 2,
        height: Number(userForm.height),
        weight: Number(userForm.weight),
        age: Number(userForm.age),
        goal: formatGoalForAPI(userForm.goal),
        role: formatRoleForAPI(userForm.role || 'user'),
        dailyCalorieGoal: Number(userForm.dailyCalories),
      email: userForm.email,
      activityLevel: userForm.activityLevel
    }
    
    console.log(`正在更新用户 ID: ${userForm.id}，数据:`, userData);
    const response = await updateUser(userForm.id, userData);
    console.log('用户信息更新响应:', response.data);
    
    if (response.data && response.data.error === 0) {
      infoModalTitle.value = '操作成功';
      infoModalMessage.value = '用户信息更新成功！';
      infoModalSuccess.value = true;
      showInfoModal.value = true;
    } else {
      throw new Error(response.data?.message || '更新失败，但未返回具体错误信息');
    }
    
    closeEditUserModal() // 关闭编辑模态框
    fetchUserList()
  } catch (error) {
    console.error('保存用户信息失败:', error);
    infoModalTitle.value = '操作失败';
    let backendMessage = '未知错误';
    if (error.response && error.response.data && error.response.data.message) {
      backendMessage = error.response.data.message;
    } else if (error.message) {
      backendMessage = error.message;
    }
    infoModalMessage.value = '保存用户信息失败: ' + backendMessage;
    infoModalSuccess.value = false;
    showInfoModal.value = true;
  }
}

function loadSearchHistory() {
  const savedHistory = localStorage.getItem('user_search_history');
  if (savedHistory) {
    try {
      searchHistory.value = JSON.parse(savedHistory).slice(0, 5);
    } catch (e) {
      console.error('解析搜索历史失败', e);
      searchHistory.value = [];
    }
  }
}

function saveToSearchHistory(query) {
  if (!query || !query.trim()) return;
  const updatedHistory = [query.trim()];
  searchHistory.value.forEach(item => {
    if (item !== query.trim() && updatedHistory.length < 5) {
      updatedHistory.push(item);
    }
  });
  searchHistory.value = updatedHistory;
  localStorage.setItem('user_search_history', JSON.stringify(updatedHistory));
}

function selectFromHistory(query) {
  searchQuery.value = query;
  showSearchHistory.value = false;
  applyFilters();
}

function triggerAvatarUpload() {
  avatarInputRef.value.click();
}

async function handleAvatarFileChange(event) {
  const token = localStorage.getItem('admin_token');
  if (!token) {
    infoModalTitle.value = '操作失败';
    infoModalMessage.value = '您尚未登录或登录已过期，请重新登录后再试。';
    infoModalSuccess.value = false;
    showInfoModal.value = true;
    avatarInputRef.value.value = ''; 
    return;
  }

  const file = event.target.files[0];
  if (!file) {
    return;
  }

  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  if (!allowedTypes.includes(file.type)) {
    infoModalTitle.value = '上传失败';
    infoModalMessage.value = '不支持的文件类型。请上传 JPG, PNG, GIF, 或 WEBP 格式的图片。';
    infoModalSuccess.value = false;
    showInfoModal.value = true;
    avatarInputRef.value.value = ''; 
    return;
  }

  if (file.size > 5 * 1024 * 1024) { // 5MB
    infoModalTitle.value = '上传失败';
    infoModalMessage.value = '文件大小不能超过 5MB。';
    infoModalSuccess.value = false;
    showInfoModal.value = true;
    avatarInputRef.value.value = '';
    return;
  }

  try {
    infoModalTitle.value = '正在上传';
    infoModalMessage.value = '头像正在上传中，请稍候...';
    infoModalSuccess.value = true; 
    showInfoModal.value = true;

    let targetUserId = null;
    // 编辑用户信息时，为当前正在编辑的用户上传头像
    if (userForm.id) { // 直接使用 userForm.id 来判断是否为编辑模式
      targetUserId = userForm.id;
    }

    const response = await uploadAvatar(file, targetUserId);
    
    if (response && response.error === 0 && response.body && response.body.avatarUrl) {
      userForm.avatar = getFullAvatarUrl(response.body.avatarUrl); 
      infoModalTitle.value = '上传成功';
      infoModalMessage.value = '头像上传成功！新的头像URL已更新。';
      infoModalSuccess.value = true;
    } else {
      throw new Error(response?.message || '头像上传失败，但未返回具体错误信息。');
    }
    showInfoModal.value = true; 

  } catch (error) {
    console.error('头像上传处理失败:', error);
    infoModalTitle.value = '上传失败';
    infoModalMessage.value = '头像上传失败: ' + (error.message || '未知错误');
    infoModalSuccess.value = false;
    showInfoModal.value = true;
  } finally {
    avatarInputRef.value.value = ''; 
  }
}
</script>

<style scoped>
/* 可选的组件内样式 */
</style> 